/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Controller;

import java.net.Socket;
import java.io.IOException;
import java.net.UnknownHostException;

/**
 *
 * @author Sinem
 * July - 2011
 */
public class URLController {

  private String m_sErrMsg;

  public URLController ()
  {
      m_sErrMsg = "";
  }
  
  public boolean checkURL(String sURL) 
  {      
      boolean bValid = true; // URL is valid or not
      Socket socket = null; // to check availability
      boolean bAvailable = false;
      
      if(sURL.startsWith("www.")== false)
      {
          //Address is not correctly typed
          m_sErrMsg = "URL is not typed correctly.";
          bValid = false;
      }     
      else if((sURL.endsWith(".gov.tr")== false) && (sURL.startsWith(".org.tr")== false))
      {
          // Address does not belong to a public instution web site
          m_sErrMsg = "This URL does not belong to a Public Institution Web Site";
          bValid = false;
      }
      else
      {
          //check if there is a currently broadcasting web site from the given URL, or not
          try {
              //try to connect
              socket = new Socket(sURL, 80);
              bAvailable = true;
          } catch (UnknownHostException e) {
          } catch (IOException e) {
          } finally {
              if (socket != null) {
                  try {
                      socket.close();
                  } catch (IOException e) {
                  }
              }
          }
          if (bAvailable == false) {
              //connection failed
              m_sErrMsg = "Web Site is not available";
              bValid = false;
          }
      }            
      return bValid;
  }
  
  public String getErrMsg()
  {
      return m_sErrMsg;
  }
}
